package com.ggb.reactive.service

import com.ggb.reactive.domain.dto.EmployeePageQueryDTO
import com.ggb.reactive.domain.entity.Employee
import com.ggb.reactive.model.PageResult
import com.ggb.reactive.model.Result
import lombok.RequiredArgsConstructor
import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.PageRequest
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate
import org.springframework.data.relational.core.query.Criteria
import org.springframework.data.relational.core.query.Query
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono

@Service
@RequiredArgsConstructor
class EmployeeService(private val r2dbcEntityTemplate: R2dbcEntityTemplate) {

    fun findEmployeeByCriteria(employeePageQueryDTO: EmployeePageQueryDTO): Mono<Result<PageResult<Employee>>> {
        var criteria = Criteria.empty()

        employeePageQueryDTO.name?.let {
            criteria = criteria.and("name").like("%$it%")
        }

        val pageable = PageRequest.of(employeePageQueryDTO.page - 1, employeePageQueryDTO.pageSize)


        val query = Query.query(criteria).with(pageable)
        val countQuery = Query.query(criteria)

        return r2dbcEntityTemplate.select(query, Employee::class.java)
            .map{
                it.password="***"
                it
            }
            .collectList()

            .zipWith(r2dbcEntityTemplate.count(countQuery, Employee::class.java))

            .map { tuple -> PageImpl(tuple.t1, pageable, tuple.t2) }
            .map { page ->
                // 将Page<User>转换为你的PageResult<User>（假设你有一个类似的结构）
                Result.success(PageResult(total = page.totalElements, records = page.content))
            }
    }

}